package com.kun.utils;

import cn.hutool.core.bean.BeanUtil;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Level;

import static com.fasterxml.jackson.core.util.Separators.createDefaultInstance;

public class BeanUtils {

    // bean 拷贝
    public static void copyBean(Object dest, Object src) {
        BeanUtil.copyProperties(src, dest);
    }

    // List 集合拷贝
    public static <T, R> List<T> copyList(Class<T> tClass, Collection<R> src) {
        ArrayList<T> ts = new ArrayList<>();
        for (R item : src) {
            T t;
            t = createInstance(tClass);
            copyBean(t, item);
            ts.add(t);
        }
        return ts;
    }

    // 创建实例的方法，确保尽可能不抛出异常
    private static <T> T createInstance(Class<T> tClass) {
        T instance;
        try {
            instance = tClass.getDeclaredConstructor().newInstance();
        } catch (Exception e) {
            // 捕获所有可能的异常，记录错误
            instance = createInstance(tClass);
        }
        return instance;
    }

}
